package main

import (
	"fmt"
	"log"
	"net"
	"strings"
)

const response_body = `<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Web Server-Goroutine</title>
  </head>
  <body>
    <h2 style="color: blue">Welcome to the Echo Server</h2>
  </body>
</html>
`
const response_header = `HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: %d
Connection: keep-alive
Server: YZY.com

%s`

// func getImage() []byte {
// 	header := `HTTP/1.1 200 OK
// 	Content-Type := image/jpeg

// %v`
// 	headerLen := len(header)
// 	bodyLen := len(图片位置)
// 	response := make([]byte, headerLen+bodyLen)
// []byte(header) copy
// 	ima content copy -> responsebodyLen
// return
// }

var response = fmt.Sprintf(
	strings.ReplaceAll(response_header, "\n", "\r\n"),
	len(response_body), response_body,
)

func main() {
	// fmt.Println(response)
	laddr, err := net.ResolveTCPAddr("tcp4", "0.0.0.0:9999")
	if err != nil {
		log.Fatal(err)
	}
	server, err := net.ListenTCP("tcp4", laddr) // 底层非阻塞 socket 创建，bind、listen GMP
	if err != nil {
		log.Fatal(err)
	}
	defer server.Close()

	for {
		conn, err := server.Accept() // 非阻塞的了，用法是阻塞的用法
		if err != nil {
			fmt.Println(err)
			continue // goto END
		}

		go func(conn net.Conn) { // connection per goroutine
			defer conn.Close()
			buffer := make([]byte, 4096)
			n, err := conn.Read(buffer)
			if err != nil {
				fmt.Println(err)
			}
			if n == 0 { // 客户端主动断开
				return
			}
			data := buffer[:n]
			// 相当于浏览器发来的 HTTP 请求，解析
			// 根据 URL method -> 不同的函数处理返回响应的数据
			request_first, _, _ := strings.Cut(string(data), "\r\n")
			fmt.Println(data)
			firstLine := strings.Split(request_first, " ")
			path := firstLine[1]
			fmt.Println(path)
			// request.path request.method
			// if path == "/pic/a.jpg" && request.method == "GET" {
			// 	// 应该做到去文件系统找对应的图片文件
			// 	conn.Write(getImage())
			// }
			conn.Write([]byte(response)) // 响应
		}(conn)

	}
}
